package com.visual.open.anpr.server.controller.server.restful;

import com.visual.open.anpr.server.controller.server.impl.PlateControllerImpl;
import com.visual.open.anpr.server.domain.common.ResponseInfo;
import com.visual.open.anpr.server.domain.request.PlateInfoReqVo;
import com.visual.open.anpr.server.domain.response.PlateInfoRepVo;
import com.visual.open.anpr.server.utils.ResponseBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.jmimemagic.*;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;

@Api(tags="01、车牌识别服务")
@RestController("visualPlateController")
@RequestMapping("/visual/plate")
public class PlateController extends PlateControllerImpl {

    @ApiOperation(value="1、车牌识别", position = 1)
    @Override
    @ResponseBody
    @RequestMapping(value = "/recognition", method = RequestMethod.POST)
    public ResponseInfo<List<PlateInfoRepVo>> recognition(@RequestBody @Valid PlateInfoReqVo plateInfoReq) {
        return super.recognition(plateInfoReq);
    }


    @ApiOperation(value="2、上传文件车牌识别", position = 2)
    @PostMapping("/rec")
    public ResponseInfo<List<PlateInfoRepVo>> recognition(@ApiParam("车牌图片") @RequestPart(value = "file") MultipartFile image,
                                                          @ApiParam("最大搜索条数：默认5") @RequestParam(required = false) Integer limit) {
        try {
            String base64EncoderImg = Base64.encodeBase64String(image.getBytes());
            MagicMatch match = Magic.getMagicMatch(image.getBytes(), false);

            base64EncoderImg = "data:" + match.getMimeType() + ";base64," + base64EncoderImg;
            PlateInfoReqVo plateInfoReqVo = new PlateInfoReqVo(base64EncoderImg, limit);
            return super.recognition(plateInfoReqVo);
        } catch (Exception e) {
            logger.error("plate recognition exception:", e);
            return ResponseBuilder.exception(e.getMessage(), null);
        }

    }
}
